import Container from '@icedesign/container';
import React, { Component } from 'react';
import { Message, Grid, Dialog, Button, Input, Upload, Pagination, Icon, Search, Radio } from '@alifd/next';
import { FormBinderWrapper, FormBinder, FormError } from '@icedesign/form-binder';
import IceImg from '@icedesign/img';
import request from '../../../../instances/request';
import Cookies from 'universal-cookie';

const cookies = new Cookies();

const { Row, Col } = Grid;

class NoticeList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataSource: [],
      isLoading: true,
      totalPage: 1,
      totalCount: 0,
      currentPage: 1,
      value: {},
      realFileName: '',
      sStr: '',
    };
  }

  static defaultProps = {
    limit: 8,
    showEditButton: false,
  };

  async handlePageChange( page ) {
    await this.getNotificationList(this.props.limit, page);
  };

  async getNotificationList( limit, page ) {
    let res = await request.post('/notification/list', {
      limit: limit,
      page: page,
      sStr: this.state.sStr,
    }).catch((err) => {   // 这里catch了之后一定要reject
      Message.error(`文件列表接口${err}`);
      return Promise.reject(err);
    });
    console.log("文件列表接口", res);

    const { code, msg } = res.data;
    switch ( code ) {
      case 0:
        let { fileList, totalCount, count } = msg;
        this.setState({
          dataSource: fileList,
          isLoading: false,
          totalCount,
          totalPage: Math.round(totalCount / this.props.limit),
          currentPage: page,
        });
        break;
      default:
        Message.error(`文件列表接口code${code}`);
        return;
    }
  }

  onFormChange(value) {
    this.setState({
      value,
    })
  }

  hookAddOrUpdateDialog(value, action) {
    const self = this;
    this.setState({
      value,
      realFileName: value.realFileName,
    }, () => {
      let dialog = Dialog.show({
        isFullScreen: true,
        shouldUpdatePosition: true,
        title: '添加公告',
        content: (
          <FormBinderWrapper
            value={this.state.value}
            onChange={this.onFormChange.bind(this)}
          >
            <div className="dashboard-dialog">
              <div style={styles.formItem}>
                <div style={styles.formLabel}>公告标题</div>
                <FormBinder
                  name="title"
                  required
                  message="标题必填"
                >
                  <Input style={{ width: '300px' }} placeholder="请填写公告标题"/>
                </FormBinder>
                <FormError name="title" />
              </div>
              <div style={styles.formItem}>
                <div style={styles.formLabel}>是否置顶</div>
                <FormBinder
                  name="priority"
                  required
                  message="必选"
                >
                  <Radio.Group
                    dataSource={[{
                      label: '是',
                      value: 2,
                    },{
                      label: '否',
                      value: 1,
                    }]}
                  />
                </FormBinder>
                <FormError name="priority" />
              </div>
              <div style={styles.formItem}>
                <div style={styles.formLabel}>文件</div>
                <FormBinder
                  name="files"
                  required
                  message="文件必上传"
                >
                  <Upload.Dragger
                    beforeUpload={(file, options) => {
                      return {
                        headers: {
                          token: cookies.get('token')
                        }
                      }
                    }}
                    listType="text"
                    action="/api/file/upload"
                    onSuccess={() => {
                      Message.success('文件上传成功');
                    }}
                    onError={() => {
                      Message.error('文件上传失败');
                    }}
                    limit={1}
                    autoUpload={true}
                    formatter={(res, file) => {
                      let { code, msg } = res;
                      self.setState({
                        realFileName: msg.filename,
                      });
                      return {
                        success: code === 0,
                        url: `/files/${msg.filename}`,
                      }
                    }}
                  />
                </FormBinder>
                <FormError name="files" />
              </div>
            </div>
          </FormBinderWrapper>
        ),
        onOk: () => {
          if(!this.state.value.title || !this.state.value.files || this.state.value.files.length === 0) {
            Message.warning("表单不能为空");
            return false;  // 返回null即关闭
          }
          return request
            .post(action === 'add' ? '/notification/add': '/notification/update', {
              id: this.state.value.id,
              title: this.state.value.title,
              files: this.state.value.files,
              priority: this.state.value.priority,  // 是否置顶
              realFileName: this.state.realFileName,  // 带有前缀的真实的文件名，为了方便删除文件
            }).then((res) => {
              let { code, msg } = res.data;
              if( code !== 0 ) {
                throw new Error(`首页通知添加接口code为${code}`);
              }
              Message.success(action === 'add' ? '添加公告成功': '修改公告成功');
              return this.getNotificationList(this.props.limit, this.state.currentPage);
            });
        },
        onCancel: () => {
          dialog.hide();
        }
      });
    });
  }

  handleDeleteItem(value) {
    let { id } = value;
    let dialog = Dialog.confirm({
      content: '您确认删除这一条目吗？',
      onOk: () => {
        return request
          .post('/notification/delete',{
            id,
          }).then((res) => {
            let { code, msg } = res.data;
            if( code !== 0 ) {
              throw new Error(`首页通知删除接口code为${code}`);
            }
            Message.success('删除公告成功');
            return this.getNotificationList(this.props.limit, this.state.currentPage);
          });
      },
      onCancel: () => {
        dialog.hide();
      },
    })
  }

  downloadFile(file) {
    window.downloadFile(file.downloadUrl);
  }

  async componentDidMount() {
    await this.getNotificationList(this.props.limit, this.state.currentPage);
  }

  render() {
    return (
      ! this.state.isLoading &&
      <Container style={{ padding: '0 0 20px 0', marginBottom: '10px' }}>
        <Row>
          <Col>
            <div style={{ height: '60px', background: '#EAEBEF' }}>
              <div style={
                {
                  float: 'left',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  height: '60px',
                  lineHeight: '60px',
                  paddingLeft: '30px',
                }
              }>
                <IceImg width={22} height={22} src={require('../../images/notice.svg')} style={{ display: 'inline', verticalAlign: 'middle' }}/>
                <span style={{ display: 'inline', verticalAlign: 'middle' }}>&nbsp;平台公告</span>
              </div>
              <div style={{
                float: 'right',
                lineHeight: '60px',
                marginRight: '20px',
              }}>
                <Search
                  style={{ width: '180px' }}
                  shape='simple'
                  placeholder={'输入标题按Enter查找'}
                  onChange={(sStr) => {
                    this.setState({
                      sStr
                    });
                  }}
                  onSearch={() => {
                    return this.getNotificationList(this.props.limit, 1);
                  }}
                />
                {
                  this.props.showEditButton &&
                  <Button
                    style={{ marginLeft: '20px' }}
                    type="primary"
                    onClick={this.hookAddOrUpdateDialog.bind(this, { priority: 1 }, 'add')}
                  >
                    添加公告
                  </Button>
                }
              </div>
            </div>
          </Col>
        </Row>
        <div>
          {this.state.dataSource.map((file, index) => {
            return (
              <div className='notice' key={index} style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                borderBottom: '1px solid #efefef',
                padding: '0 20px 0 30px',
              }}>
                <a
                  key={index}
                  target="_blank"
                  rel="noopener noreferrer"
                  title={file.title}
                  href={file.downloadUrl}
                  style={
                    this.props.showEditButton ?
                      {
                        marginRight: '40px',
                        ...styles.noticeItem,
                      } :
                      {
                        ...styles.noticeItem,
                      }
                  }
                >
                  <div>
                    <span style={styles.title}>{file.title}</span>
                    {
                      file.priority === 2 &&
                      <span style={{
                        ...styles.tag,
                        ...styles.top,
                        marginLeft: '30px'
                      }}>
                      置顶
                    </span>
                    }
                  </div>
                  <span style={styles.time}>
                    { file.createdTime }
                  </span>
                </a>
                <div
                  style={
                    this.props.showEditButton ?
                      {
                        width: '120px',
                        textAlign: 'center',
                        lineHeight: '40px',
                      } :
                      {
                        width: '60px',
                        textAlign: 'center',
                        lineHeight: '40px',
                      }
                  }
                >
                    <span
                      style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
                      onClick={this.downloadFile.bind(this, file)}
                    >
                      下载
                    </span>
                  {
                    this.props.showEditButton &&
                    <span style={styles.separator}/>
                  }
                  {
                    this.props.showEditButton &&
                    <span
                      style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
                      onClick={this.hookAddOrUpdateDialog.bind(this, file, 'update')}
                    >
                      编辑
                    </span>
                  }
                  {
                    this.props.showEditButton &&
                    <span style={styles.separator}/>
                  }
                  {
                    this.props.showEditButton &&
                    <span
                      style={{ color: 'rgba(49, 128, 253, 0.65)', cursor: 'pointer' }}
                      onClick={this.handleDeleteItem.bind(this, file)}
                    >
                      删除
                    </span>
                  }
                  {/*<span*/}
                  {/*onClick={this.hookAddOrUpdateDialog.bind(this, file, 'update')}*/}
                  {/*title="编辑"*/}
                  {/*style={styles.operBtn}*/}
                  {/*>*/}
                  {/*<Icon size="xs" type="edit" />*/}
                  {/*</span>*/}
                  {/*<span*/}
                  {/*onClick={this.handleDeleteItem.bind(this, file)}*/}
                  {/*title="删除"*/}
                  {/*style={styles.operBtn}*/}
                  {/*>*/}
                  {/*<Icon size="xs" type="close" />*/}
                  {/*</span>*/}
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ textAlign: 'right', paddingRight: '20px', paddingTop: '10px' }}>
          <Pagination
            shape='no-border'
            type="simple"
            onChange={this.handlePageChange.bind(this)}
            total={this.state.totalCount}
            hideOnlyOnePage={true}
            pageSize={this.props.limit} />
        </div>
      </Container>
    );
  }
}

const styles = {
  header: {
    fontSize: 18,
    lineHeight: '30px',
    paddingBottom: 20,
    fontWeight: 700,
  },
  noticeItem: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    lineHeight: 40,
    width: '100%',
    height: 40,
    textDecoration: 'none',
  },
  tag: {
    fontSize: 12,
    lineHeight: '16px',
    marginLeft: 5,
    padding: '2px 8px',
    borderRadius: 20,
  },
  top: {
    backgroundColor: '#eff6ff',
    color: '#5e83fb',
  },
  hot: {
    backgroundColor: '#ffe8e8',
    color: '#ee706d',
  },
  new: {
    backgroundColor: '#fff4e2',
    color: '#f7da47',
  },
  title: {
    color: '#333',
    lineHeight: '40px',
    height: '40px',
  },
  time: {
    color: '#999',
    lineHeight: '40px',
    height: '40px',
  },
  formItem: {
    marginBottom: '20px',
    display: 'flex',
    alignItems: 'center',
  },
  formLabel: {
    width: '85px',
    marginRight: '10px',
    textAlign: 'left',
    flexShrink: '0',
  },
  formError: {
    marginLeft: '10px',
    width: '30px',
  },
  operBtn: {
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  separator: {
    margin: '0 4px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
};

export default NoticeList;
